#include "getid.h"

char *substring(char *ch, int pos, int length)
{
    //定义字符指针 指向传递进来的ch地址
    char *pch = ch;
    //通过calloc来分配一个length长度的字符数组，返回的是字符指针。
    char *subch = (char *)calloc(sizeof(char), length + 1);
    int i;
    //只有在C99下for循环中才可以声明变量，这里写在外面，提高兼容性。
    pch = pch + pos;
    //是pch指针指向pos位置。
    for (i = 0; i < length; i++)
    {
        subch[i] = *(pch++);
        //循环遍历赋值数组。
    }
    subch[length] = '\0'; //加上字符串结束符。
    return subch;         //返回分配的字符数组地址。
}

void searchTableData(MYSQL mysql, char *column, char *Tname, char *where, int *id)
{
    char sql[1024] = {0};
    sprintf(sql, "SELECT %s FROM %s WHERE %s", column, Tname, where);
    printf("查询sql语句:%s\n", sql);
    int ret = mysql_query(&mysql, sql);
    if (ret)
    {
        printf("查询表数据失败！失败原因：%s\n",
               mysql_error(&mysql));
        return;
    }
    MYSQL_RES *result = mysql_store_result(&mysql);
    if (result == NULL)
    {
        printf("返回\n");
        return;
    }

    MYSQL_ROW row = mysql_fetch_row(result);
    if (row == NULL)
    {
        printf("row空,返回\n");
        return;
    }
    printf("row[0] = %s\n", row[0]);
    *id = atoi(row[0]);
    mysql_free_result(result);
}

int findID(MYSQL mysql,char *pwd)
{
    int pidw = 0; //开始根节点pid=0
    printf("pwd = %s\n", pwd);
    int len = strlen(pwd);
    char* gtfilename;
    int j = 0;
    int k = 1;
    int ID[256] = {0};
    char rule[1024] = {0};
    for (int i = 0; i < len; i++)
    {
        printf("pwd[%d] = %c\n", i, pwd[i]);
        if (pwd[i] == '/')
        {
            memset(&rule, 0, 1024);
            gtfilename = substring(pwd, k, i-k);
            k = i + 1;
            printf("gtfilename = %s\n", gtfilename);

            sprintf(rule, "filename = \"%s\" and parent_id = %d", gtfilename, pidw); //开始根节点pid=-1
            printf("rule = %s\n", rule);
            int id = 0;
            searchTableData(mysql, "id", "virtualfile", rule, &id);
            ID[j] = id;
            printf("ID[%d]:%d\n", j, ID[j]);
            pidw = ID[j];
            j++;
        }
    }
    printf("k = %d,len = %d\n", k, len);
    gtfilename = substring(pwd, k, len-k+1);
    printf("gtfilename:%s\n", gtfilename);
    sprintf(rule, "filename = \"%s\" and parent_id = %d", gtfilename, pidw);
    int id = 0;
    searchTableData(mysql, "id", "virtualfile", rule, &id);
    pidw = id;
    return pidw;
}